# -*- coding: utf-8 -*-
"""
Created on Sat Aug 22 14:33:13 2020

@author: Farman
"""


import sys
import pathlib
 
base_dir = pathlib.Path(sys.argv[0]).absolute().parent.parent

if sys.path.count(base_dir) == 0:
    sys.path.append(str(base_dir))


from CommonBase import ModisHdfFileMan
from Auxes      import MakeDeepDir
from Auxes      import ListFiles 
import os
import sys

#-----------------------------------------------------------------------------

def save_str_list(str_list, file):
    str_list = [s.rstrip('\n') + '\n' for s in str_list]
    open(file, 'w').writelines(str_list)
    
    if sys.platform != 'win32':
        os.system('chmod +x %s'%file)
    return
  
#-----------------------------------------------------------------------------
    
# python GribVsmTran.py era5_grib_file_of_day dest_dump_file

def gen_script(era5_grib_path, dest_path, script_save_path, script_num):
    '''
    .
    '''
    script_num = int(script_num)
    
    # prepare modis file manager
    #era5_grib_file_list_file = pathlib.Path(sys.argv[0]).absolute().parent / 'file_list.txt'
    era5_files = ListFiles.list_files_recursive(era5_grib_path, '*.grib')
    
    if not pathlib.Path(script_save_path).exists():    
        MakeDeepDir.make_path(script_save_path)
    
    if sys.platform == 'win32':
        os.system(r'del %s\*'%script_save_path)
    else:
        os.system(r'rm %s/*'%script_save_path)
    
    # generate commands
    commands = []
    
    for file in era5_files:
        dest_file = pathlib.Path(file).name + '.joblib'
        dest_file = pathlib.Path(dest_path) / dest_file
        
        if sys.platform == 'win32':
            command = 'python %s\\GribVsmTran.py %s %s\n'%(pathlib.Path(sys.argv[0]).absolute().parent,
                                                 file, dest_file)
        else:
            command = 'python %s/GribVsmTran.py %s %s\n'%(pathlib.Path(sys.argv[0]).absolute().parent,
                                                 file, dest_file)
        commands.append(command)
        
    # group commands into script_num groups
    group_commands = [[] for n in range(script_num)]
    
    for n in range(len(commands)):
        group_commands[n % script_num].append(commands[n])
    
    # add pbs head lines
    def add_pbs_head(input_lines, name):
        lines = []
        lines.append('#!/bin/bash')
        lines.append('#PBS -N %s'%name)
        lines.append('#PBS -l nodes=2:ppn=64')
        lines.append('#PBS -q front')
        lines.append('#PBS -o %s.log'%name)
        lines.append('#PBS -e %s.err'%name)
        lines.append('#PBS -l walltime=888:00:00')
        return lines + input_lines
    
    script_files = [] # for linux back ground running
    
    # save script file
    for n in range(script_num):
        script_file = 'bat_%02d.pbs'%n
        script_file = pathlib.Path(script_save_path) / script_file
        print('Saving', script_file)
        group_commands[n] = add_pbs_head(group_commands[n], script_file)
        save_str_list(group_commands[n], script_file)
        script_files.append(str(script_file))
    
    script_files = ['qsub %s&'%s for s in script_files]
    script_files.insert(0, 'rm %s/*.log'%script_save_path)
    script_files.insert(0, 'rm %s/*.err'%script_save_path)
    script_file = pathlib.Path(script_save_path) / 'qsub_add.run'
    print('Saving', script_file)
    save_str_list(script_files, script_file)    
    return group_commands
    

#-----------------------------------------------------------------------------
#'''
if sys.platform == 'win32':
    modis_hdf_path = r'D:\CUIT-NewFarman\Data\MOD09A1-h27v05'
    year = 2019
    day_of_year = 361
    dest_path = r'D:\CUIT-NewFarman\CodeCurrent\DroughtNDVI_MOD09A1\drought_hdf'
    script_save_path  = r'D:\CUIT-NewFarman\CodeCurrent\DroughtNDVI_MOD09A1\script'
    script_num = 4    
else:
    era5_grib_path = '/data/yule/ERA5'
    dest_path = '/data/yule/disk2/ProgramData/ERA5_VSM_dump'
    script_save_path = '/public/home/yule/code/team-w/DroughtVegDRI/script'
    script_num = 16

gen_script(era5_grib_path, dest_path, script_save_path, script_num)

'''
if __name__ == '__main__':
    if len(sys.argv) != 7:
        print('\nUsage')
        print('-' * 40)
        print('    python gen_script.py modis_hdf_path year day_of_year dest_path script_save_path script_num')
        print()
    else:
        modis_hdf_path, year, day_of_year, dest_path, script_save_path, script_num = sys.argv[1:]
        gen_lai_drought_script(modis_hdf_path, year, day_of_year, dest_path, script_save_path, script_num)
#'''
